#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include "jansson.h"

#define MAX_JSON_SIZE   (512 * 1024)
#define MAX_BUF_SIZE    (256 * 1024)

/* input: file content
 * output: one line string, removed spaces, replace '\n' with '\\'
 * */
static void file2line(char *input, char *output)
{
    int i = 0, j = 0;
    int in_space = 0;

    while (input[i]) {
        if (input[i] == ' ' || input[i] == '\t') {
            if (!in_space) {
                output[j++] = ' ';
                in_space = 1;
            }
            i++;
        } else {
            output[j++] = input[i++];
            in_space = 0;
        }
    }

    output[j] = '\0';
}

int loadfile(char *buf, int maxsize, char *file)
{
    int fd = open(file, O_RDONLY);
    if (fd < 0) {
        goto failed;
    }

    memset(buf, 0, maxsize);
    maxsize--;

    int len = 0;
    int ret = 0;

    for (;;) {
        ret = read(fd, buf + len, maxsize - len);
        if (ret < 0) {
            printf("[read] `%s` failed\n", file);
            goto close;
        }

        len += ret;
        if (ret == 0) {
            close(fd);
            file2line(buf, buf);
            return len;
        }
    }

close:
    close(fd);

failed:
    return -1;
}

struct param {
    int json_indent;
};

int main(int argc, char *argv[])
{
    json_t *json_root;
    char *json_str;

    time_t rawtime;
    struct tm *timeinfo;

    char *buf = (char *)malloc(MAX_BUF_SIZE);
    if (buf == NULL) {
        return -1;
    }

    memset(buf, 0, MAX_BUF_SIZE);

    json_root = json_object();
    if (!json_root) {
        fprintf(stderr, "无法创建 JSON 对象\n");
        return -1;
    }

    //json_object_set_new(json_root, "age", json_integer(30));
#if 1
    time(&rawtime);
    timeinfo = localtime(&rawtime);
    strftime(buf, MAX_BUF_SIZE, "%Y-%m-%d %H:%M:%S\n", timeinfo);
#endif
    json_object_set_new(json_root, "datetime", json_string(buf));

#define json_add_str(_key, _file) \
    do { \
        loadfile(buf, MAX_BUF_SIZE, _file); \
        json_object_set_new(json_root, _key, json_string(buf)); \
    } while(0)

    /*
       loadfile(buf, MAX_BUF_SIZE, "/proc/uptime");
       json_object_set_new(json_root, "uptime", json_string(buf));
       */

    json_add_str("uptime", "/proc/uptime");
    json_add_str("loadavg", "/proc/loadavg");
    json_add_str("meminfo", "/proc/meminfo");

    json_str = json_dumps(json_root, JSON_INDENT(0));

    printf("%s\n", json_str);

    free(json_str);
    json_decref(json_root);

    return 0;
}
